var path = require('path');
var fs = require('fs');
var express = require('express');
const http = require('http');
const https = require('https')
var bodyParser = require('body-parser')
var imgReq = require('./img-req.js');
const d_mysql = require('./mysql.js');
// 引入os
var os = require('os');
const {
    db_mysql,
    errorData,
    enCodePWD,
    historyProduct,
    urlIndentify,
    host,
    port,
    port1,
    projectName
} = require('./common-req.js')
const { StringDecoder } = require('string_decoder');
const decoder = new StringDecoder('utf8');
// 获取操作系统
var routerReq = require('./router-req.js')
// 引入crypto模块
const crypto = require('crypto');
let key = fs.readFileSync(path.join(__dirname, '/ssl/server.key'), 'utf8'),
    cert = fs.readFileSync(path.join(__dirname, '/ssl/server.pem'), 'utf8');
// 创建证书对象
let cas = { key, cert };

var plantKnow = express();
// create application/json parser
plantKnow.use(bodyParser.json());
// create application/x-www-form-urlencoded parser
plantKnow.use(bodyParser.urlencoded({
    extended: false
}));
console.log(path.join(__dirname, ''))
console.log()
const staticPath = path.resolve('', path.join(__dirname, ''), '../public');
plantKnow.use('/plantknow/public', express.static(staticPath));
let plantKnowHttp = http.createServer(plantKnow);
let plantKnowHttps = https.createServer(cas, plantKnow);
// 跨域设置
plantKnow.all("*", function(req, res, next) {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Headers',
        'ontent-Type,Content-Length,Authorization,Accept,X-Requested-With');
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
    res.header('X-Powered-By', '3.2.1')
    
    if (req.method == 'OPTIONS') res.send(200);
    // /让options请求快速返回/
    else {
        console.log(req.query)
        let token = req.query.token ? req.query.token : req.body.token;
        let phone = req.query.phone ? req.query.phone : req.body.phone;
        let indentify = urlIndentify(req.originalUrl);
        if(indentify) {
            // 没有phone和token信息
            if(!phone || !token) {
                errorData.msg = '身份鉴定失败1'
                res.send(errorData)
                return;
            }
            let tokenSql = 'select token from users where phone=?';
            db_mysql.select(tokenSql, phone, tokenRes => {
                if(tokenRes && tokenRes.length > 0) {
                    let tk = tokenRes[0].token;
                    let tp = enCodePWD(token, tk) // 解密出来手机号
                    if(phone === tp) {
                        next();
                    } else {
                        errorData.msg = '身份鉴定失败2'
                        res.send(errorData)
                    }
                } else {
                    errorData.msg = '身份鉴定失败3'
                    res.send(errorData)
                }
            })
        } else {
            next()
        }
    }
});

plantKnow.use('/plantknow/users', routerReq.loginRegisterReq);
plantKnow.use('/plantknow/doors', routerReq.doorReq);
plantKnow.use('/plantknow/outline', routerReq.outlineReq);
plantKnow.use('/plantknow/section', routerReq.sectionReq);
plantKnow.use('/plantknow/genus', routerReq.genusReq);
plantKnow.use('/plantknow/botanys/condition', routerReq.botanyReq);
plantKnow.use('/plantknow/upload/plant', routerReq.imgReq);
plantKnow.use('/plantknow/reptile', routerReq.reptileReq);
plantKnow.use('/plantknow/history', routerReq.historyReq);
plantKnow.use('/plantknow/recommend/plant', routerReq.hisProdReq);


plantKnowHttp.listen(port, host, function() {
    console.log("服务器启动成功！-- http://" + host + ":" + port + "/" + projectName)
})
plantKnowHttps.listen(port1, host, function() {
    console.log("服务器启动成功！-- https://" + host + ":" + port1 + "/" + projectName)
})

// const ws = require('nodejs-websocket');
// let wsArr = [];
// let pageNum = 1;
// let pageSize = 10;
// const server = ws.createServer(connection => {
//     // console.log(server.connections)
//     connection.on("text", function (data) {
//         // console.log(connection)
//         console.log('str', data)
        
//         let userInfo = JSON.parse(data);
//         wsArr.push({
//             phone: userInfo.phone,
//             ws: connection
//         })
//         // console.log(connection)
// 		// console.log('我来接收客户端发过来的消息' + str)
// 		// connection.sendText(str);//返回给客户端的数据
// 		// server.connections.forEach(function (conn) {
// 		// 	conn.sendText(str)//返回给所有客户端的数据(相当于公告、通知)
// 		// })
//         setInterval(() => {
//             pageNum = pageNum % 2;
//             wsArr.forEach(item => {
//                 const phone = item.phone;
//                 let selSql = 'select * from historyview where phone=? limit 0, 50';
//                 let selArr = [phone];
//                 let resData = {
//                     data: [],
//                     msg: '获取推荐数据成功',
//                     status: 0,
//                     code: 200
//                 }
//                 db_mysql.select(selSql, selArr, async results => {
//                     let data = await historyProduct(results, pageNum, pageSize);
//                     data.forEach(item => {
//                         let base = decoder.write(item.baseInfo);
//                         let grow = decoder.write(item.growInfo);
//                         let form = decoder.write(item.formInfo);
//                         let cul = decoder.write(item.cultivateInfo);
//                         var obj = {
//                             botanyId: item.botanyId,
//                             doorId: item.doorId,
//                             outlineId: item.outlineId,
//                             sectionId: item.sectionId,
//                             genusId: item.genusId,
//                             name: item.name,
//                             baseInfo: base === '' ? base : JSON.parse(base),
//                             growInfo: grow === '' ? grow : JSON.parse(grow),
//                             formInfo: form === '' ? form : JSON.parse(form),
//                             cultivateInfo: cul === '' ? cul : JSON.parse(cul),
//                             sectionId: item.sectionId,
//                             src: item.src,
//                             time: item.time
//                         }
//                         resData.data.push(obj);
//                     })
//                     item.ws.sendText(JSON.stringify(resData))
//                     pageNum++;
//                 })
//             })
//         }, 1000 * 60 * 10)
//     })
//     //监听关闭
//     connection.on("close", function (code, reason) {
//         console.log("Connection closed")
//     })
//     //监听异常
// 	connection.on("error",() => {
// 		console.log('服务异常关闭...')
// 	})
// }).listen(8002, 'http://' + host, () => {
//     console.log('监听ws')
// })
// function broadcast(server, msg) {
//     server.connections.forEach(function (conn) {
//         conn.sendText(msg)
//     })
// }

// 监听socket连接
// io.on('connection', function (socket) {
// 	// 当某用户连上socket服务时，给他打个招呼
// 	 // nodejs的underscore扩展中的findWhere方法，可以在对象集合中，通过对象的属性值找到该对象并返回
// 	// var toSocket = _.findWhere(io.sockets.sockets, {id: toId});
//     // sendMsgToUser(socket, {
//     //     msg: `你好${socket.id}`
//     // })
//    console.log('a socket')
//    socket.on('setCard', function(data) {  //记录用户连接的身份,并保存
// 	   console.log(data)
// 	   connectArr[data.userId] = socket.id;
// 	   console.log("记录", data.userId, connectArr[data.userId])
// 	   broadcast({
// 		   msg: `欢迎${data.userName}加入聊天室...`
// 	   })
//    })
//     // 监听用户发的聊天内容
//     socket.on('chat', function (data) {
// 	    // 然后广播给其他用户：某某某说了什么
// 		console.log(data)
// 		sendMsgToRoom(io, data);
//     });
//     // 监听socket连接断开
//     socket.on('disconnect', (reason) => {
	  
//     });
// });
